﻿using System;
using System.Collections.Generic;
using System.Linq;
using SenileCoderMvc.Library.Models;

namespace SenileCoderMvc.Library.DataAccess
{
    public class DefaultDao : ISupportsDataAccess
    {
        private readonly IMakesSessionFactories makesSessionFactories;

        public DefaultDao(IMakesSessionFactories makesSessionFactories)
        {
            this.makesSessionFactories = makesSessionFactories;
        }

        public List<string> GetObjects()
        {
            return new List<string>
                       {
                           "one",
                           "two",
                           "three",
                       };
        }

        public IQueryable<T> Query<T>(IQueryObject<T> query)
            where T : IModel
        {
            var sessionFactory = makesSessionFactories.GetSessionFactory();
            return query.Query(sessionFactory.OpenSession());
        }

        public T GetById<T>(object id)
            where T : IModel
        {
            var sessionFactory = makesSessionFactories.GetSessionFactory();
            return sessionFactory.OpenSession().Get<T>(id);
        }

        public void SaveOrUpdate<T>(T t) where T : IModel
        {
            var session = makesSessionFactories.GetSessionFactory().OpenSession();

            using (var tx = session.BeginTransaction())
            {
                session.SaveOrUpdate(t);
                tx.Commit();
            }
        }

        public void DeleteEntity<T>(T t)
            where T : IModel
        {
            var session = makesSessionFactories.GetSessionFactory().OpenSession();
            using (var tx = session.BeginTransaction())
            {
                session.Delete(t);
                tx.Commit();
            }
        }
    }
}
